'use client';

import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import diff from 'microdiff';
import type { IConfigSite, IDifference } from '@/interfaces';
import { updateSiteConfig } from '@/services/api';
import useToast from '@/hooks/useToast';
import { getDiffData } from '@/lib/tool';
import Box from '@/app/[locale]/admin/common/box';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function UpdateConfigSite({
  source,
  translatedFields,
}: {
  source: IConfigSite;
  translatedFields: PrefixedTTranslatedFields<'configAdminPage'>;
}) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    helpLink?: string;
    feedbackLink?: string;
    reportLink?: string;
    githubLink?: string;
    mpImageLink?: string;
    disableRegistration?: boolean;
  }>({
    helpLink: source.helpLink ?? '',
    feedbackLink: source.feedbackLink ?? '',
    reportLink: source.reportLink ?? '',
    githubLink: source.githubLink ?? '',
    mpImageLink: source.mpImageLink ?? '',
    disableRegistration: source.disableRegistration ?? false,
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const [isDisabledSave, setIsDisabledSave] = useState(true);

  const updateSiteConfigMutation = useMutation(updateSiteConfig);

  useEffect(() => {
    const diffData = diff(
      {
        helpLink: source.helpLink ?? '',
        feedbackLink: source.feedbackLink ?? '',
        reportLink: source.reportLink ?? '',
        githubLink: source.githubLink ?? '',
        mpImageLink: source.mpImageLink ?? '',
        disableRegistration: source.disableRegistration ?? false,
      },
      form,
    );
    setDifferenceData(diffData);
    setIsDisabledSave(diffData.length === 0);
  }, [form, source]);

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const data = getDiffData(differenceData);
      await updateSiteConfigMutation.mutateAsync({
        data,
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.operate.updateCompleted,
      });
    } catch (e) {
      updateSiteConfigMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setDifferenceData([]);
    }
  }

  function onChangeForm(e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) {
    const name = e.target.name;
    const value = e.target.value;

    if (name === 'disableRegistration') {
      setForm({ ...form, disableRegistration: value === 'true' });
    } else {
      setForm({ ...form, [name]: value });
    }
  }

  return (
    <Box>
      <form onSubmit={onClickSave} className="vstack gap-4">
        <div>
          <label className="form-label">
            {translatedFields.config.site.helpLink}
          </label>
          <input
            type="text"
            className="form-control"
            name="helpLink"
            value={form.helpLink}
            onChange={onChangeForm}
            aria-describedby="helpLink"
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.config.site.feedbackLink}
          </label>
          <input
            type="text"
            className="form-control"
            name="feedbackLink"
            value={form.feedbackLink}
            onChange={onChangeForm}
            aria-describedby="feedbackLink"
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.config.site.reportLink}
          </label>
          <input
            type="text"
            className="form-control"
            name="reportLink"
            value={form.reportLink}
            onChange={onChangeForm}
            aria-describedby="reportLink"
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.config.site.githubLink}
          </label>
          <input
            type="text"
            className="form-control"
            name="githubLink"
            value={form.githubLink}
            onChange={onChangeForm}
            aria-describedby="githubLink"
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.config.site.mpImageLink}
          </label>
          <input
            type="text"
            className="form-control"
            name="mpImageLink"
            value={form.mpImageLink}
            onChange={onChangeForm}
            aria-describedby="mpImageLink"
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.config.site.disableRegistration}
          </label>
          <select
            name="disableRegistration"
            value={form.disableRegistration ? 'true' : 'false'}
            onChange={onChangeForm}
            className="form-select"
            aria-label="disableRegistration"
          >
            <option value="true">true</option>
            <option value="false">false</option>
          </select>
        </div>

        <button
          type="submit"
          disabled={updateSiteConfigMutation.isLoading || isDisabledSave}
          className="btn btn-success col col-lg-2 my-4"
        >
          {updateSiteConfigMutation.isLoading && <Spinner classs="me-2" />}
          {translatedFields.operate.update}
        </button>
      </form>
    </Box>
  );
}
